package com.plian.system.service.pm.property;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.alibaba.excel.write.metadata.fill.FillWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.plian.Tools.*;
import com.plian.Tools.office.WordUtil;
import com.plian.Tools.pagedata.PageData;
import com.plian.system.bean.pm.ContributorInfoWordBean;
import com.plian.system.common.status.CustomCode;
import com.plian.system.config.exception.MyRuntimeException;
import com.plian.system.constant.baseinfo.ValueSetConstant;
import com.plian.system.dao.bt.baseinfo.BaseInfoDao;
import com.plian.system.dao.pm.contributor.ContributorBasicsDao;
import com.plian.system.dao.pm.partneroutbound.PartnerOutboundBasicsDao;
import com.plian.system.dao.pm.partnersituation.PartnerSituationBascicsDao;
import com.plian.system.dao.pm.property.PropertyBasicsDao;
import com.plian.system.dao.pm.property.PropertyDao;
import com.plian.system.dao.pm.propertychange.PropertyChangeDao;
import com.plian.system.dao.pm.shareholding.ShareholdingBasicsDao;
import com.plian.system.dao.sys.file.FileDao;
import com.plian.system.dao.sys.orgzation.OrgzationDao;
import com.plian.system.entity.pm.property.PropertyRecord;
import com.plian.system.entity.sys.OrgRelation;
import com.plian.system.mapper.pm.property.PropertyRecordMapper;
import com.plian.system.mapper.sys.OrgRelationMapper;
import com.plian.system.model.CommonCode;
import com.plian.system.model.ListResult;
import com.plian.system.model.ObjResult;
import com.plian.system.model.page.Page;
import com.plian.system.properties.GzwProperties;
import com.plian.system.service.bt.baseinfo.BaseInfoService;
import com.plian.system.service.sys.orgzation.OrgzationService;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class PorpertyBasicsService {
    @Autowired
    PropertyBasicsDao propertyBasicsDao;
    @Autowired
    ContributorBasicsDao contributorBasicsDao;
    @Autowired
    ShareholdingBasicsDao shareholdingBasicsDao;
    @Autowired
    PartnerSituationBascicsDao partnerSituationBascicsDao;
    @Autowired
    PartnerOutboundBasicsDao partnerOutboundBasicsDao;
    @Autowired
    BaseInfoDao baseInfoDao;
    @Autowired
    FileDao fileDao;
    @Autowired
    OrgzationDao orgzationDao;
    @Autowired
    PropertyDao propertyDao;
    @Autowired
    BaseInfoService baseInfoService;

    @Autowired
    OrgRelationMapper orgRelationMapper;
    @Autowired
    OrgzationService orgzationService;

    @Autowired
    Environment environment;

    @Autowired
    PropertyChangeDao propertyChangeDao;

    @Resource
    PropertyRecordMapper propertyRecordMapper;

    @Autowired
    private GzwProperties gzwProperties;

    private static final Logger log = LoggerFactory.getLogger(PorpertyBasicsService.class);

    public ObjResult tree() {
        try {
            List<PageData> arrayList = new ArrayList<>();
            PageData propertyPd = new PageData();
            propertyPd.put("orgId", TokenUtil.getTokenOrgId());
            propertyPd.put("competentOrganization", TokenUtil.getCompetentOrganization());
            PageData pd = propertyBasicsDao.findByOrgIdAndCom(propertyPd);
            if (pd != null) {
                TreeUtli treeUtli = new TreeUtli();
                List<PageData> list_all = propertyBasicsDao.list(null);
                List<PageData> l = treeUtli.getChlid1(pd.getString("id"), list_all);
                pd.put("children", l);
                arrayList.add(pd);
            }
            PageData p = new PageData();
            p.put("list", arrayList);
            ObjResult objResult = new ObjResult(CommonCode.SUCCESS);
            objResult.setPageData(p);
            return objResult;
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw new MyRuntimeException();
        }
    }

    public ObjResult simpleTree() {
        List<PageData> arrayList = getSimpleTree();
        PageData p = new PageData();
        p.put("list", arrayList);
        ObjResult objResult = new ObjResult(CommonCode.SUCCESS);
        objResult.setPageData(p);
        return objResult;

    }

//    public ObjResult mixedTree(MixTreeDto dto){ TODO DEL
//        List<PageData> result = new ArrayList<>();
//        //产权树
//        List<PageData> simpleTree = getSimpleTree();
//        if (CollectionUtil.isNotEmpty(simpleTree)){
//            //混改企业Id
//            Set<String> mixOrgIds = new HashSet<>();
//
//            List<SubsidiaryMixedReform> mixedReforms = subsidiaryMixedReformMapper.selectList(new LambdaQueryWrapper<SubsidiaryMixedReform>()
//                    .eq(SubsidiaryMixedReform::getStatus, 3).eq(SubsidiaryMixedReform::getIsLatest, 2)
//                    .eq(Optional.ofNullable(dto.getFunctionalCategoryId()).isPresent(),SubsidiaryMixedReform::getFunctionalCategoryId,dto.getFunctionalCategoryId()));
//            if (CollectionUtil.isNotEmpty(mixedReforms)) {
//                Set<String> mixedIds = mixedReforms.stream().map(SubsidiaryMixedReform::getMixedEnterpriseId).collect(Collectors.toSet());
//                mixOrgIds.addAll(mixedIds);
//            }
//            List<SubsidiaryIntroduceReform> introduceReforms = subsidiaryIntroduceReformMapper.selectList(new LambdaQueryWrapper<SubsidiaryIntroduceReform>()
//                    .eq(SubsidiaryIntroduceReform::getStatus, 3)
//                    .eq(Optional.ofNullable(dto.getFunctionalCategoryId()).isPresent(),SubsidiaryIntroduceReform::getFunctionalCategoryId,dto.getFunctionalCategoryId()));
//            if (CollectionUtil.isNotEmpty(introduceReforms)) {
//                Set<String> introduceIds = introduceReforms.stream().map(SubsidiaryIntroduceReform::getCompanyId).collect(Collectors.toSet());
//                mixOrgIds.addAll(introduceIds);
//            }
//            if (CollectionUtil.isNotEmpty(mixOrgIds)){
//                for (PageData pageData:simpleTree){
//                    setIsMixed(pageData,mixOrgIds);
//                    if (pageData.containsKey("children")){
//                        removeNotMixed((List<PageData>) pageData.get("children"));
//                        result.add(pageData);
//                    }
//                }
//            }
//        }
//        PageData p = new PageData();
//        p.put("list", result);
//        ObjResult objResult = new ObjResult(CommonCode.SUCCESS);
//        objResult.setPageData(p);
//        return objResult;
//    }

    /**
     * @Author: Take-off
     * @Description: //TODO 减去非混改产权
     * @Date: 3:10 PM 2023/2/23
     * @Param: [children]
     * @return: void
     **/
    private void removeNotMixed(List<PageData> children){
        if (CollectionUtil.isNotEmpty(children)){
            for (int i = children.size() -1; i>=0 ;i--){
                PageData pageData = children.get(i);
                if (pageData.containsKey("children")){
                    List<PageData> child = (List<PageData>) pageData.get("children");
                    if (CollectionUtil.isNotEmpty(child)){
                        removeNotMixed(child);
                        if (CollectionUtil.isEmpty(child)){
                            pageData.remove("children");
                            if (pageData.getInteger("isMix") == 0){
                                children.remove(pageData);
                            }
                        }
                    }else {
                        pageData.remove("children");
                        if (pageData.getInteger("isMix") == 0){
                            children.remove(pageData);
                        }
                    }
                }else {
                    if (pageData.getInteger("isMix") == 0){
                        children.remove(pageData);
                    }
                }
            }
        }
    }

    /**
     * @Author: Take-off
     * @Description: //TODO 打上混改标记
     * @Date: 3:09 PM 2023/2/23
     * @Param: [pageData, mixIds]
     * @return: void
     **/
    private void setIsMixed(PageData pageData,Set<String> mixIds){
        if (pageData.containsKey("children")){
            List<PageData> children = (List<PageData>) pageData.get("children");
            for (PageData pd:children){
                setIsMixed(pd,mixIds);
            }
        }
        //匹配混改Id
        if (mixIds.contains(pageData.getString("id"))){
            pageData.put("isMix",1);
        }else {
            pageData.put("isMix",0);
        }

    }

    /**
     * @Author: Take-off
     * @Description: //TODO 获取产权树
     * @Date: 2:03 PM 2023/2/23
     * @Param: []
     * @return: java.util.List<com.plian.Tools.pagedata.PageData>
     **/
    private List<PageData> getSimpleTree(){
        List<PageData> arrayList = new ArrayList<>();
        PageData pageData = new PageData();
        pageData.put("orgId", TokenUtil.getTokenOrgId());
        pageData.put("competentOrganization", TokenUtil.getCompetentOrganization());

        try {
            List<PageData> gzwOrgs = orgzationDao.findByName(gzwProperties.getName());
            String gzwId = "";
            if (CollectionUtil.isNotEmpty(gzwOrgs)) {
                gzwId = gzwOrgs.get(0).getString("id");
            }
            PageData pd = propertyBasicsDao.findSimpleByOrgId(pageData);
            if (pd != null) {
                if (gzwId.equals(TokenUtil.getCompetentOrganization())) {
                    pd.put("gzwFlag", 1);
                } else {
                    pd.put("gzwFlag", 2);
                }
                List<PageData> list_all = propertyBasicsDao.simpleList(null);
                Map<Integer, List<PageData>> levelMap = list_all.stream()
                        .collect(Collectors.groupingBy(propertyBasic -> propertyBasic.getInteger("propertyLevel")));
                PageData root = new PageData();
                if (CollectionUtil.isNotEmpty(list_all)) {
                    for (PageData property : list_all) {
                        if (gzwId.equals(property.getString("competentOrganization"))) {
                            property.put("gzwFlag", 1);
                        } else {
                            property.put("gzwFlag", 2);
                        }
                        if (pd.getString("id").equals(property.getString("id"))) {
                            root = property;
                        }

                        Integer level = property.getInteger("propertyLevel");
                        if (levelMap.containsKey(level + 1)) {
                            List<PageData> levelList = levelMap.get(level + 1);
                            List<PageData> tempList = new ArrayList<>();
                            tempList.addAll(levelList);
                            String parentId = property.getString("id");
                            List<PageData> children = new ArrayList<>();
                            for (PageData child : tempList) {
                                if (child.getString("parentId").equals(parentId)) {
                                    children.add(child);
                                    levelList.remove(child);
                                }
                            }
                            if (CollectionUtil.isNotEmpty(children)) {
                                property.put("children", children);
                            }
                        }
                        property.remove("propertyLevel");


                    }
                }
                arrayList.add(root);
            }
        }catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw new MyRuntimeException();
        }
        return arrayList;
    }

    public ObjResult relationTree() {
        try {
            List<PageData> arrayList = new ArrayList<>();
            PageData propertyPd = new PageData();
            propertyPd.put("orgId", TokenUtil.getTokenOrgId());
            propertyPd.put("competentOrganization", TokenUtil.getCompetentOrganization());
            PageData pd = propertyBasicsDao.findByOrgIdAndCom(propertyPd);
            if (pd != null) {
                TreeUtli treeUtli = new TreeUtli();
                List<PageData> list_all = propertyBasicsDao.list(null);

                List<OrgRelation> orgRelations = orgRelationMapper.selectList(new QueryWrapper<OrgRelation>().eq("type", 2));

                if (CollectionUtil.isNotEmpty(orgRelations)){
                    Map<String, String> map = orgRelations.stream().collect(Collectors.toMap(OrgRelation::getOrgId, OrgRelation::getParentId));
                    for (PageData property : list_all){
                        if (map.containsKey(property.getString("id"))){
                            property.put("parentId", map.get(property.getString("id")));
                        }
                    }
                }

                List<PageData> l = treeUtli.getChlid1(pd.getString("id"), list_all);
                pd.put("children", l);
                arrayList.add(pd);
            }
            PageData p = new PageData();
            p.put("list", arrayList);
            ObjResult objResult = new ObjResult(CommonCode.SUCCESS);
            objResult.setPageData(p);
            return objResult;
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw new MyRuntimeException();
        }
    }

    public ObjResult simpleRelationTree() {
        try {
            List<PageData> arrayList = new ArrayList<>();
            PageData pageData = new PageData();
            pageData.put("orgId", TokenUtil.getTokenOrgId());
            pageData.put("competentOrganization", TokenUtil.getCompetentOrganization());
            PageData pd = propertyBasicsDao.findSimpleByOrgId(pageData);

            List<PageData> gzwOrgs = orgzationDao.findByName(gzwProperties.getName());
            String gzwId = "";
            if (CollectionUtil.isNotEmpty(gzwOrgs)){
                gzwId =gzwOrgs.get(0).getString("id");
            }

            if (pd != null) {
                TreeUtli treeUtli = new TreeUtli();
                if (gzwId.equals(TokenUtil.getCompetentOrganization())){
                    pd.put("gzwFlag", 1);
                }else {
                    pd.put("gzwFlag", 2);
                }
                List<PageData> list_all = propertyBasicsDao.simpleList(null);

                List<OrgRelation> orgRelations = orgRelationMapper.selectList(new QueryWrapper<OrgRelation>().eq("type", 2));
                Map<Integer, List<PageData>> levelMap = list_all.stream()
                        .collect(Collectors.groupingBy(propertyBasic -> propertyBasic.getInteger("propertyLevel")));
                PageData root= new PageData();
                Map<String, String> map = new HashMap<>();
                List<String> changeChildIds = new ArrayList<>();
                List<String> changeParentIds = new ArrayList<>();
                Map<String, PageData> tempMap = new HashMap<>();
                boolean flag = false;
                if (CollectionUtil.isNotEmpty(orgRelations)) {
                    flag = true;
                    map = orgRelations.stream().collect(Collectors.toMap(OrgRelation::getParentId, OrgRelation::getOrgId));
                    changeChildIds = orgRelations.stream().map(OrgRelation::getOrgId).collect(Collectors.toList());
                    changeParentIds = orgRelations.stream().map(OrgRelation::getParentId).collect(Collectors.toList());
                }
                List<PageData> changeParentPd = new ArrayList<>();
                for (PageData property : list_all){
                    if (gzwId.equals(property.getString("competentOrganization"))){
                        property.put("gzwFlag", 1);
                    }else {
                        property.put("gzwFlag", 2);
                    }
                    if (pd.getString("id").equals(property.getString("id"))){
                        root = property;
                    }


                    Integer level = property.getInteger("propertyLevel");
                    if (levelMap.containsKey(level + 1)){
                        List<PageData> levelList = levelMap.get(level + 1);
                        List<PageData> tempList = new ArrayList<>();
                        tempList.addAll(levelList);
                        String parentId = property.getString("id");
                        List<PageData> children = new ArrayList<>();
                        for (PageData child : tempList){
                            if (child.getString("parentId").equals(parentId)){
                                if (flag && changeChildIds.contains(child.getString("id"))){
                                    tempMap.put(child.getString("id"), child);
                                }else {
                                    children.add(child);
                                }
                                levelList.remove(child);
                            }

                        }
                        if (CollectionUtil.isNotEmpty(children)){
                            property.put("children", children);
                        }
                        if (flag && changeParentIds.contains(property.getString("id"))){
                            changeParentPd.add(property);
                        }

                    }

                    property.remove("propertyLevel");
                }

                for (PageData parent : changeParentPd){
                    String id = parent.getString("id");
                    String childId = map.get(id);
                    List<PageData> children = new ArrayList<>();
                    if (parent.containsKey("children")){
                        children = (List<PageData>)parent.get("children");
                    }
                    children.add(tempMap.get(childId));
                }

                arrayList.add(root);
            }
            PageData p = new PageData();
            p.put("list", arrayList);
            ObjResult objResult = new ObjResult(CommonCode.SUCCESS);
            objResult.setPageData(p);
            return objResult;
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw new MyRuntimeException();
        }
    }

    /**
     * 行业转换
     *
     * @return
     */
    private List<String> industryNames(String codes) throws Exception {
        List<String> l = Arrays.asList(codes.split(","));
        List<PageData> baseInfo = baseInfoDao.findbycodes(l);
        List l1 = new ArrayList();
        for (String code : l) {
            String s1 = "";
            for (PageData pageData : baseInfo) {
                if (pageData.getString("code").equals(code)) {
                    s1 = pageData.getString("name");
                    break;
                }
            }
            l1.add(s1);
        }
        return l1;
    }

    /**
     * 行业转换
     *
     * @return
     */
    private List<String> industryNames(String codes, List<Tree> list) throws Exception {
        String[] l = codes.split(",");
        List l1 = new ArrayList();
        for (String code : l) {
            String s1 = "";
            for (Tree pageData : list) {
                if (pageData.getCode().equals(code)) {
                    s1 = pageData.getName();
                    break;
                }
            }
            l1.add(s1);
        }
        return l1;
    }


    public ObjResult findbyidAll(PageData pd) {
        String pro_id = pd.getString("id");
        //附件
        try {
            PageData p = propertyBasicsDao.findbyid(pro_id);
            p.put("netWorkingName", netWorkingName(p.getString("netWorking")));
            p.put("stateFundedRelationName", stateFundedRelationName(p.getString("stateFundedRelation")));
            p.put("functionalCategoryNameName", functionalCategoryNameName(p.getString("functionalCategoryName")));
            //出资人情况
            List<PageData> list_con = contributorBasicsDao.find_parentId(pro_id);
            if (("1").equals(p.getString("nature"))) {
                List<PageData> list_share = shareholdingBasicsDao.find_parentId(pro_id);
                p.put("list_share", list_share);
            }
            if (("2").equals(p.getString("nature"))) {
                List<PageData> list_PartnerSituation = partnerSituationBascicsDao.find_parentId(pro_id);
                p.put("listPartnerSituation", list_PartnerSituation);
                List<PageData> list_PartnerOutbound = partnerOutboundBasicsDao.find_parentId(pro_id);


                List<String> parentId1 = new ArrayList<>();
                parentId1.add("110");
                PageData p_o1 = new PageData();
                p_o1.put("parentId", parentId1);
                List<Tree> l = baseInfoDao.findTree(p_o1);

                for (PageData pageData : list_PartnerOutbound) {
                    String industry = pageData.getString("industry");
                    if (Tools.notEmpty(industry)) {
                        pageData.put("industryName", industryNames(industry, l));
                        pageData.put("industry", Arrays.asList(industry.split(",")));
                    }
                }
                p.put("listPartnerOutbound", list_PartnerOutbound);
            }

            if (Tools.notEmpty(p.getString("majorIndustries"))) {
                p.put("majorIndustriesNames", industryNames(p.getString("majorIndustries")));
                p.put("majorIndustries", Arrays.asList(p.getString("majorIndustries").split(",")));
            } else {
                p.put("majorIndustriesNames", new ArrayList<>());
                p.put("majorIndustries", new ArrayList<>());
            }

//            p.put("majorIndustriesNames", industryNames(p.getString("majorIndustries")));
//            p.put("majorIndustries", Arrays.asList(p.getString("majorIndustries").split(",")));
            p.put("list_con", list_con);
            fileList(p);
            ObjResult objResult = new ObjResult(CommonCode.SUCCESS);
            objResult.setPageData(p);
            return objResult;
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw new MyRuntimeException();
        }

    }

    private String netWorkingName(String netWorking){
        Map<String, String> netWorkingMap = baseInfoService.getChildMap(ValueSetConstant.NET_WORKING_TYPE);
        if (com.plian.Tools.StringUtil.isNotBlank(netWorking) && netWorkingMap.containsKey(netWorking)) {
            return netWorkingMap.get(netWorking);
        }
        return "";
    }

    private String stateFundedRelationName(String stateFundedRelation){
        Map<String, String> stateFundedRelationMap = baseInfoService.getChildMap(ValueSetConstant.STATE_FUNDED_RELATION);
        return stateFundedRelationName(stateFundedRelationMap, stateFundedRelation);
    }

    private String stateFundedRelationName(Map<String, String> stateFundedRelationMap,  String stateFundedRelation){
        if (com.plian.Tools.StringUtil.isNotBlank(stateFundedRelation) && stateFundedRelationMap.containsKey(stateFundedRelation)) {
            return stateFundedRelationMap.get(stateFundedRelation);
        }
        return "";
    }

    private String functionalCategoryNameName(String functionalCategoryName){
        Map<String, String> functionalCategoryNameMap = baseInfoService.getChildMap(ValueSetConstant.FUNCTIONAL_CATEGORY);
        if (com.plian.Tools.StringUtil.isNotBlank(functionalCategoryName) && functionalCategoryNameMap.containsKey(functionalCategoryName)) {
            return functionalCategoryNameMap.get(functionalCategoryName);
        }
        return "";
    }

    public ObjResult findbyid(PageData pd) {
        try {
            PageData p = propertyBasicsDao.findbyid(pd.getString("id"));
            p.put("netWorkingName", netWorkingName(p.getString("netWorking")));
            p.put("stateFundedRelationName", stateFundedRelationName(p.getString("stateFundedRelation")));
            ObjResult objResult = new ObjResult(CommonCode.SUCCESS);
            objResult.setPageData(p);
            return objResult;
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw new MyRuntimeException();
        }
    }

    public ObjResult findByorgId(PageData pd) {
        try {
            String orgId = TokenUtil.getTokenOrgId();
            if (Optional.ofNullable(pd).isPresent()
                    && StringUtil.isNotBlank(pd.getString("orgId"))) {
                orgId = pd.getString("orgId");
            }
//            PageData p = propertyBasicsDao.findByorgId(orgId);
            PageData propertyPd = new PageData();
            propertyPd.put("orgId", orgId);
            propertyPd.put("competentOrganization", TokenUtil.getCompetentOrganization());
            PageData p = propertyBasicsDao.findByOrgIdAndCom(propertyPd);
            if (p == null){
                return new ObjResult(CustomCode.builder().message("请先完成产权登记！").code(1999).success(false).build());
            }
//            String orgGradation1 = p.getString("orgGradation");
//            if(StringUtils.isBlank(orgGradation1)){
//                return new ObjResult(CustomCode.builder().message("企业级次未找到，请先通过【产权变更】完善相关产权信息！").code(1999).success(false).build());
//            }
            if ("0".equals(p.getString("nature"))) {
                p.put("currency", "014001");
                p.put("domesticOverseas", "004001");
            }
            if ("1".equals(p.getString("nature"))) {
                p.put("domesticOverseas", "004002");
            }
            p.put("monetaryUnit", "013002");

            if (Optional.ofNullable(p).isPresent()) {
                if(StringUtil.isNotBlank(p.getString("majorIndustries"))){//会有为空的情况 所以判空
                    p.put("majorIndustriesNames", industryNames(p.getString("majorIndustries")));
                }
                if(StringUtil.isNotBlank(p.getString("majorIndustries"))){//会有为空的情况 所以判空
                    p.put("majorIndustries", Arrays.asList(p.getString("majorIndustries").split(",")));
                }

                String orgGradation = p.getString("orgGradation");
                Map<String, String> rankMap = baseInfoService.getChildMap(ValueSetConstant.ENTERPRISE_RANK);
                if (StringUtil.isNotBlank(orgGradation) && rankMap.containsKey(orgGradation)) {
                    p.put("orgGradationName", rankMap.get(orgGradation));
                }
            }
            ObjResult objResult = new ObjResult(CommonCode.SUCCESS);
            objResult.setPageData(p);
            return objResult;
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw new MyRuntimeException();
        }
    }

    public ListResult findByorgName(PageData pd) {
        try {
            List<PageData> list = propertyBasicsDao.findByorgName(pd.getString("orgName"));
            ListResult objResult = new ListResult(CommonCode.SUCCESS);
            objResult.setList(list);
            return objResult;
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw new MyRuntimeException();
        }
    }

    public ListResult listAll() {
        try {
            PageData pd = new PageData();
            pd.put("competentOrganization", TokenUtil.getCompetentOrganization());

            List<PageData> gzwOrgs = orgzationDao.findByName(gzwProperties.getName());
            String gzwId = "";
            if (CollectionUtil.isNotEmpty(gzwOrgs)){
                gzwId =gzwOrgs.get(0).getString("id");
            }

            List<PageData> list = propertyBasicsDao.list(pd);
            if (CollectionUtil.isNotEmpty(list)){
                for (PageData property : list){
                    if (gzwId.equals(property.getString("competentOrganization"))) {
                        property.put("gzwFlag", 1);
                    }else {
                        property.put("gzwFlag", 2);
                    }

                }
            }
            ListResult objResult = new ListResult(CommonCode.SUCCESS);
            objResult.setList(list);
            return objResult;
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw new MyRuntimeException();
        }
    }
    private void fileList(PageData pd) throws Exception {
        List<PageData> l = fileDao.findParentId(pd.getString("recordId"));
        for (int i = 1; i <= 9; i++) {
            List<PageData> l2 = new ArrayList<>();
            for (PageData pageData : l) {
                if (pageData.getString("type").equals("f" + i)) {
                    pageData.put("itFileName", pageData.getString("fileName"));
                    pageData.put("viewFileName", pageData.getString("fileName"));
                    String fileName = pageData.getString("fileName");
                    //文件后缀
                    String fileTyle = fileName.substring(fileName.lastIndexOf("."));
                    if (!"pdf".equalsIgnoreCase(fileTyle)) {
                        BigDecimal bigDecimal = new BigDecimal(pageData.getString("fileSize"));
                        BigDecimal b = bigDecimal.divide(new BigDecimal("1048576"), 2, RoundingMode.HALF_UP);
                        if (b.floatValue() <= 20) {
                            pageData.put("isPrint", true);
                        } else {
                            pageData.put("isPrint", false);
                        }
                    } else {
                        pageData.put("isPrint", true);
                    }

                    if (Tools.notEmpty(fileName)) {
                        fileName = fileName.substring(19);
                        pageData.put("fileName", fileName);
                    }
                    l2.add(pageData);
//                    break;
                }
            }
            pd.put("f" + i, l2);
        }
    }


    public ListResult orgListPage(PageData pd) {
        try {
            Page page = new Page(true, pd);
            List<PageData> list = propertyBasicsDao.orgListPage(page);
            ListResult listResult = new ListResult(CommonCode.SUCCESS);
            listResult.setList(list);
            listResult.setTotal(page.getTotal());
            return listResult;
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw new MyRuntimeException();
        }
    }

    /**
     * 修改单位
     *
     * @param pd
     * @return
     */
    @Transactional(rollbackFor = RuntimeException.class)
    public ObjResult editByOrgId(PageData pd) {
        try {
            propertyBasicsDao.editByOrgId(pd);
            propertyDao.editByOrgId(pd);
            ObjResult objResult = new ObjResult(CommonCode.SUCCESS);
            return objResult;
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw new MyRuntimeException();
        }
    }

    @Transactional(rollbackFor = RuntimeException.class)
    public ObjResult editByOrgIdAll() {
        try {
            List<PageData> list_org = orgzationDao.list(null);
            List<PageData> list_pro = propertyBasicsDao.list(null);
            List<PageData> list_change = propertyChangeDao.allList();
            List<PropertyRecord> propertyRecords = propertyRecordMapper.selectList(null);

            List<PageData> list = new ArrayList<>();
            List<PageData> listChange = new ArrayList<>();
            List<PropertyRecord> listRecord = new ArrayList<>();
            for (PageData org : list_org) {
                String competentOrganization = orgzationService.getCompetentOrganization(org, list_org, org.getString("id"));
                for (PageData pro : list_pro) {
                    if (org.getString("name").equals(pro.getString("orgName"))
                    && competentOrganization.equals(pro.getString("competentOrganization"))) {
                        PageData pd = new PageData();
                        pd.put("id", pro.getString("id"));
                        pd.put("name", pro.getString("orgName"));
                        pd.put("orgId", org.getString("orgId"));
                        pd.put("orgName", org.getString("name"));
                        list.add(pd);
                        break;
                    }
                }
                //修改propertyChange
                for (PageData change : list_change) {
                    if (org.getString("name").equals(change.getString("orgName"))
                            && competentOrganization.equals(change.getString("competentOrganization"))) {
                        PageData pd = new PageData();
                        pd.put("id", change.getString("id"));
                        pd.put("name", change.getString("orgName"));
                        pd.put("orgId", org.getString("orgId"));
                        pd.put("orgName", org.getString("name"));
                        listChange.add(pd);
                        break;
                    }
                }
                //修改record表
                for (PropertyRecord record : propertyRecords) {
                    if (org.getString("name").equals(record.getOrgName())
                            && competentOrganization.equals(record.getCompetentOrganization())) {
                        record.setOrgId(org.getString("orgId"));
                        listRecord.add(record);
                        break;
                    }
                }
            }
            if (list != null && list.size() > 0) {
                propertyBasicsDao.editByOrgIdAll(list);
                propertyDao.editByOrgIdAll(list);
            }
            if ( listChange.size() > 0) {
                propertyChangeDao.editByOrgIdAll(listChange);
            }
            if (listRecord.size() > 0){
                listRecord.forEach(m -> {
                    propertyRecordMapper.updateById(m);
                });
            }
            ObjResult objResult = new ObjResult(CommonCode.SUCCESS);
            PageData p = new PageData();
            p.put("list", list);
            objResult.setPageData(p);
            return objResult;
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw new MyRuntimeException();
        }
    }

    /**
     * 列表数据处理
     *
     * @param pd
     * @return
     * @throws Exception
     */
    private List<PageData> listData(PageData pd) throws Exception {
        if (StringUtil.isNotBlank(pd.getString("keyword"))){
            pd.put("keyword", StringUtil.cleanChars(pd.getString("keyword")));
        }
        if (StringUtil.isNotBlank(pd.getString("isMix"))){
            pd.put("isMix", StringUtil.cleanChars(pd.getString("isMix")));
        }
        if (StringUtil.isNotBlank(pd.getString("isGroup"))){
            pd.put("isGroup", StringUtil.cleanChars(pd.getString("isGroup")));
        }
        if (StringUtil.isNotBlank(pd.getString("functionalCategoryName"))){
            pd.put("functionalCategoryName", StringUtil.cleanChars(pd.getString("functionalCategoryName")));
        }
        if (pd.getString("orgGradations")!=null){
            List<String> arraysList= Arrays.asList(StringUtil.cleanChars(pd.getString("orgGradations")).replace("[","").replace("]","").split(","));
            pd.put("orgGradations",arraysList);
        }
        if (pd.get("orgCategorys")!=null){
            List<String> arraysList= Arrays.asList(StringUtil.cleanChars(pd.getString("orgCategorys")).replace("[","").replace("]","").split(","));
            pd.put("orgCategorys",arraysList);
        }
        String infoScope = pd.getString("infoScope");
        List<PageData> list;
        if ("2".equals(infoScope)){
            List<String> ids = (List<String>)pd.get("ids");
            pd.put("competentOrganizations", findCompetentOrganizations(ids));
            list = propertyBasicsDao.reportList(pd);
        }else {
            list = propertyBasicsDao.reportParentList(pd);
        }
        return valueListSet(list);
    }

    private List<String> findCompetentOrganizations(List<String> ids) throws Exception{
        List<String> competentOrganizations = new ArrayList<>();
        Map<String, PageData> allPropertyMap =  propertyBasicsDao.list(null).stream().collect(Collectors.toMap(p -> p.getString("id"), p -> p));
        if (CollectionUtil.isNotEmpty(ids)){
            for (String id : ids){
                if(allPropertyMap.containsKey(id)){
                    PageData property = allPropertyMap.get(id);
                    if (StringUtil.isNotBlank(property.getString("competentOrganization")) &&
                            !competentOrganizations.contains(property.getString("competentOrganization"))){
                        competentOrganizations.add(property.getString("competentOrganization"));
                    }
                }
            }
        }
        return competentOrganizations;
    }

    /**
     * 股权占比
     * @param contributors
     * @return
     */
    private String getContributorsStr(List<PageData> contributors, Map<String, String> contributorCategoryMap){
        if (CollectionUtil.isNotEmpty(contributors)){
            StringBuffer stringBuffer = new StringBuffer();
            for (PageData child : contributors){
                if (stringBuffer.length() != 0){
                    stringBuffer.append(StringPool.SEMICOLON);
                }
                stringBuffer.append(child.getString("contributor"));
                String category = child.getString("category");
                if (StringUtil.isNotBlank(category) && contributorCategoryMap.containsKey(category)){
                    stringBuffer.append(StringPool.LEFT_BRACKET)
                            .append(contributorCategoryMap.get(category))
                            .append(StringPool.RIGHT_BRACKET);
                }
                stringBuffer.append(child.getString("orgPaidCapital") + "万")
                        .append(BigDecimalUtil.toShortString(child.getString("equityRatio"), 2))
                        .append(StringPool.PERCENT);
            }
            return stringBuffer.toString();
        }
        return "";
    }


    private String getPartnerSituationStr(List<PageData> partnerSituationList,Map<String,String> partnerTypeMap){
        if (CollectionUtil.isNotEmpty(partnerSituationList)){
            StringBuffer stringBuffer = new StringBuffer();
            for(PageData child:partnerSituationList){
                if (stringBuffer.length() != 0){
                    stringBuffer.append(StringPool.SEMICOLON);
                }
                stringBuffer.append(child.getString("name"));
                String category = child.getString("category");
                if (StringUtil.isNotBlank(category) && partnerTypeMap.containsKey(category)){
                    stringBuffer.append(StringPool.LEFT_BRACKET)
                            .append(partnerTypeMap.get(category))
                            .append(StringPool.RIGHT_BRACKET);
                }
                String subscribedProportionStr = child.getString("subscribedProportion");
                stringBuffer.append("认缴出资额" + child.getString("subscribedCapital") + "万")
                        .append(",认缴出资比例" + BigDecimalUtil.toShortString(subscribedProportionStr, 2))
                        .append(StringPool.PERCENT);
                stringBuffer.append(",实缴出资额" + child.getString("paidCapital") + "万");
            }
            return stringBuffer.toString();
        }
        return "";
    }

    private List<PageData> valueListSet(List<PageData> list) throws Exception{
        List<PageData> l = new ArrayList<>();
        if (list != null && list.size() > 0) {
            Map<String, String> contributorCategoryMap = baseInfoService.getChildMap(ValueSetConstant.CONTRIBUTOR_CATEGORY);
            List<String> propertyIds = list.stream().map(property -> property.getString("id")).collect(Collectors.toList());
            Map<String, List<PageData>> contributorMap = new HashMap<>();
            Map<String, List<PageData>> partnerContributorMap = new HashMap<>();
            if (CollectionUtil.isNotEmpty(propertyIds)){
                List<PageData> contributors = contributorBasicsDao.findByParentIds(propertyIds);

                for (PageData contributor : contributors) {
                    List<PageData> childList = new ArrayList<>();
                    if (!contributorMap.containsKey(contributor.getString("propertyId"))){
                        contributorMap.put(contributor.getString("propertyId"), childList);
                    }
                    childList = contributorMap.get(contributor.getString("propertyId"));
                    childList.add(contributor);
                }

                List<PageData> partnerSituationList = partnerSituationBascicsDao.findByParentIds(propertyIds);

                for (PageData partnerSituation : partnerSituationList) {
                    List<PageData> childList = new ArrayList<>();
                    if (!partnerContributorMap.containsKey(partnerSituation.getString("propertyId"))){
                        partnerContributorMap.put(partnerSituation.getString("propertyId"), childList);
                    }
                    childList = partnerContributorMap.get(partnerSituation.getString("propertyId"));
                    childList.add(partnerSituation);
                }
            }
            Map<String, String> propertyIdNameMap = propertyBasicsDao.list(null).stream().collect(Collectors
                    .toMap(property -> property.getString("id"), property -> property.getString("orgName")));

            List<String> codes = new ArrayList<>();
            codes.add("002");
            codes.add("064");
            codes.add("045");
            codes.add("001");
            codes.add("060");
            PageData p_o = new PageData();
            p_o.put("parentId", codes);
            List<Tree> trees = baseInfoDao.findTree(p_o);

            PageData p_o1 = new PageData();
            List<String> hy = new ArrayList<>();
            //行业
            hy.add("110");
            p_o1.put("parentId", hy);
            List<Tree> trees1 = baseInfoDao.findTree(p_o1);
            Map<String, String> stateFundedRelationMap = baseInfoService.getChildMap(ValueSetConstant.STATE_FUNDED_RELATION);
            Map<String, String> partnerTypeMap = baseInfoService.getChildMap(ValueSetConstant.PARTNER_TYPE);
            int i = 1;
            for (PageData pro : list) {
                PageData p = new PageData();
                String nature = pro.getString("nature");
                String parentId = pro.getString("parentId");
                String parentName = "";
                if (!Tools.isEmpty(parentId) && propertyIdNameMap.containsKey(parentId)){
                    parentName = propertyIdNameMap.get(parentId);
                }
                p.put("parentName", parentName);
                p.put("capitalOrgCode", pro.getString("capitalOrgCode"));
                //序号
                p.put("index", String.valueOf(i));
                //名称
                p.put("orgName", pro.getString("orgName"));
                //统一信用编码
                p.put("orgCode", pro.getString("orgCode"));
                //国家出资企业
                p.put("stateFundedName", pro.getString("stateFundedName"));
                //国资监管机构
                String stateOwnedInstitution = pro.getString("stateOwnedInstitution");
                if (Tools.isEmpty(stateOwnedInstitution)) {
                    stateOwnedInstitution = "";
                } else {
                    stateOwnedInstitution = getBaseName(trees, stateOwnedInstitution);
                }
                p.put("stateOwnedInstitution", stateOwnedInstitution);
                //产权登记情形
                String situation = pro.getString("situation");
                String situationName = "";
                if (!Tools.isEmpty(situation)) {
                    situationName = getBaseName(trees, situation);
                }
                p.put("situationName", situationName);
                //注册日期
                p.put("aicRegDate", pro.getString("aicRegDate"));
                //工商登记日期
                p.put("aicBsDate", pro.getString("aicBsDate"));
                //注册资本
                String regCapital = Tools.notEmpty(pro.getString("regCapital")) ? pro.getString("regCapital") : "0";
                p.put("regCapital", BigDecimalUtil.toShortString(regCapital, 3));

                String fcRegCapital = Tools.notEmpty(pro.getString("fcRegCapita")) ? pro.getString("fcRegCapita") : "0";
                p.put("fcRegCapita", BigDecimalUtil.toShortString(fcRegCapital, 3));
                String id = pro.getString("id");
                p.put("contributors", "");
                p.put("originalActualCapital6","");
                p.put("actualCapital1","");
                p.put("actualCapital6","");
                p.put("originalActualCapital1","");
                if (Tools.notEmpty(nature)) {
                    //实收资本
                    if ("2".equals(nature)) {
                        String paidCapital = Tools.notEmpty(pro.getString("paidCapital")) ? pro.getString("paidCapital") : "0";
                        p.put("actualCapital6", BigDecimalUtil.toShortString(paidCapital, 4));

                       List<PageData> partnerSituationList = partnerContributorMap.get(pro.getString("id"));
                        BigDecimal sumPaidCapital = new BigDecimal(0).setScale(4, RoundingMode.UP);
                        if (CollectionUtil.isNotEmpty(partnerSituationList)){
                            for (PageData partnerSituation : partnerSituationList){
                                String category = partnerSituation.getString("category");
                                if ("078001".equals(category) ||"078002".equals(category) || "078003".equals(category) || "078004".equals(category)){
                                    sumPaidCapital = BigDecimalUtil.add(sumPaidCapital, BigDecimalUtil.toBigdecimal(partnerSituation.getString("paidCapital")));
                                }
                            }
                            p.put("contributors", getPartnerSituationStr(partnerSituationList, partnerTypeMap));
                        }
                        p.put("actualCapital1", BigDecimalUtil.toShortString(sumPaidCapital, 4));
                    } else {
                        String actualCapital6 = Tools.notEmpty(pro.getString("actualCapital6")) ? pro.getString("actualCapital6") : "0";
                        p.put("actualCapital6", BigDecimalUtil.toShortString(actualCapital6, 4));

                        String originalActualCapital6 = Tools.notEmpty(pro.getString("originalActualCapital6")) ? pro.getString("originalActualCapital6") : "0";
                        p.put("originalActualCapital6",  BigDecimalUtil.toShortString(originalActualCapital6, 4));

                        BigDecimal sumPaidCapital = new BigDecimal(0).setScale(4, RoundingMode.UP);
                        BigDecimal sumOrgPaidCapital = new BigDecimal(0).setScale(4, RoundingMode.UP);

                        if (contributorMap.containsKey(id)){
                            List<PageData> contributorList = contributorMap.get(id);
                            for (PageData contributor : contributorList){
                                String category = contributor.getString("category");
                                if ("057001".equals(category) || "057002".equals(category) || "057003".equals(category) || "057004".equals(category)){
                                    sumPaidCapital = BigDecimalUtil.add(sumPaidCapital, BigDecimalUtil.toBigdecimal(contributor.getString("orgPaidCapital")));
                                    sumOrgPaidCapital = BigDecimalUtil.add(sumOrgPaidCapital, BigDecimalUtil.toBigdecimal(contributor.getString("originalPaidCapital")));
                                }
                            }
                            p.put("contributors", getContributorsStr(contributorList, contributorCategoryMap));
                        }else{
                            p.put("contributors", "");
                        }
                        if ("1".equals(nature)){
                            p.put("originalActualCapital1", BigDecimalUtil.toShortString(sumOrgPaidCapital, 4));
                        }
                        p.put("actualCapital1", BigDecimalUtil.toShortString(sumPaidCapital, 4));
                    }
                }else{
                    p.put("contributors", "");
                }

                //组织形式
                String organizationForm = pro.getString("organizationForm");
                if (Tools.isEmpty(organizationForm)) {
                    organizationForm = "";
                } else {
                    organizationForm = getBaseName(trees, organizationForm);
                }
                p.put("organizationForm", organizationForm);
                //企业类别
                String orgCategory = pro.getString("orgCategory");
                if (Tools.isEmpty(orgCategory)) {
                    orgCategory = "";
                } else {
                    if ("045001".equals(orgCategory)){
                        p.put("isReform", "否");
                    }else {
                        p.put("isReform", "是");
                    }
                    orgCategory = getBaseName(trees, orgCategory);
                }
                p.put("orgCategory", orgCategory);
                //注册地
                p.put("regAddress", pro.getString("regAddress"));
                //所属行业
                String majorIndustries1 = pro.getString("majorIndustries");
                String majorIndustriesNames = "";
                if (Tools.notEmpty(majorIndustries1)) {
                    List<String> majorIndustries = industryNames(majorIndustries1, trees1);
                    if (list != null && list.size() > 0) {
                        majorIndustriesNames = String.join("，", majorIndustries);
                    }
                }
                p.put("majorIndustries", majorIndustriesNames);
                //产权级次
                String orgGradation = pro.getString("orgGradation");
                if (Tools.isEmpty(orgGradation)) {
                    orgGradation = "";
                } else {
                    orgGradation = getBaseName(trees, orgGradation);
                }
                p.put("orgGradation", orgGradation);
                //境内境外

                String str_nature = "";
                if (Tools.notEmpty(nature)) {
                    if ("0".equals(nature)) {
                        str_nature = "境内";
                    } else if ("1".equals(nature)) {
                        str_nature = "境外";
                    } else if ("2".equals(nature)) {
                        str_nature = "合伙人";
                        p.put("aicRegDate", pro.getString("establishmentDate"));
                    }
                }

                p.put("nature", str_nature);
                //是否混改企业
                p.put("isPrivateMix","");
                if(Tools.notEmpty(pro.getString("isPrivateMix"))){
                    p.put("isPrivateMix", "0".equals(pro.getString("isPrivateMix"))?"否":"是");
                }

                p.put("affiliatedOrgFullName","");
                if(Tools.notEmpty(pro.getString("affiliatedOrgFullName"))){
                    p.put("affiliatedOrgFullName", pro.getString("affiliatedOrgFullName"));
                }
                p.put("formType", pro.getString("formType"));
                p.put("id", pro.getString("id"));
                //是否特殊目的
                p.put("isSpecial", "");
                if(Tools.notEmpty(pro.getString("isSpecial"))){
                    p.put("isSpecial", "0".equals(pro.getString("isSpecial"))?"否":"是");
                }
                //是否混改
                p.put("isMix","");
                if(Tools.notEmpty(pro.getString("isMix"))){
                    p.put("isMix", "0".equals(pro.getString("isMix"))?"否":"是");
                }
                //是否合并
                p.put("isGroup","");
                if(Tools.notEmpty(pro.getString("isGroup"))){
                    p.put("isGroup", "0".equals(pro.getString("isGroup"))?"否":"是");
                }
                //功能分类
                p.put("functionalCategoryName","");
                String functionalCategoryName=pro.getString("functionalCategoryName");
                Map<String, String> functionCategoryNameMap = baseInfoService.getChildMap(ValueSetConstant.FUNCTIONAL_CATEGORY);
                if(Tools.notEmpty(functionalCategoryName)){
                    p.put("functionalCategoryName", functionCategoryNameMap.get(functionalCategoryName));
                }
                //是否存在个人代持股的公司
                p.put("isPersonalHolding", "");
                if(Tools.notEmpty(pro.getString("isPersonalHolding"))){
                    p.put("isPersonalHolding", "0".equals(pro.getString("isPersonalHolding"))?"否":"是");
                }
                p.put("stateFundedRelationName", stateFundedRelationName(stateFundedRelationMap, pro.getString("stateFundedRelation")));

                l.add(p);
                i++;
            }
        }
        return l;
    }

    private String getBaseName(List<Tree> list, String code) {
        String name = "";
        for (Tree tree : list) {
            if (tree.getCode().equals(code)) {
                name = tree.getName();
                break;
            }
        }
        return name;
    }

    public ListResult reportList(PageData pd) {
        try {
            List<PageData> list = listData(pd);
            ListResult listResult = new ListResult(CommonCode.SUCCESS);
            listResult.setList(list);
            return listResult;
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw new MyRuntimeException();
        }
    }

    public ListResult reportListPage(PageData pd) {
        if (StringUtil.isNotBlank(pd.getString("keyword"))){
            pd.put("keyword", StringUtil.cleanChars(pd.getString("keyword")));
        }
        if (StringUtil.isNotBlank(pd.getString("isMix"))){
            pd.put("isMix", StringUtil.cleanChars(pd.getString("isMix")));
        }
        if (StringUtil.isNotBlank(pd.getString("isGroup"))){
            pd.put("isGroup", StringUtil.cleanChars(pd.getString("isGroup")));
        }
        if (StringUtil.isNotBlank(pd.getString("functionalCategoryName"))){
            pd.put("functionalCategoryName", StringUtil.cleanChars(pd.getString("functionalCategoryName")));
        }
        if (pd.getString("orgGradations")!=null){
            List<String> arraysList= Arrays.asList(StringUtil.cleanChars(pd.getString("orgGradations")).replace("[","").replace("]","").split(","));
            pd.put("orgGradations",arraysList);
        }
        if (pd.get("orgCategorys")!=null){
            List<String> arraysList= Arrays.asList(StringUtil.cleanChars(pd.getString("orgCategorys")).replace("[","").replace("]","").split(","));
            pd.put("orgCategorys",arraysList);
        }
        String infoScope = pd.getString("infoScope");
        try {
            Page page = new Page(true, pd);
            List<PageData> list;
            if ("2".equals(infoScope)){
//                List<String> ids = (List<String>)pd.get("ids");
//                pd.put("competentOrganizations", findCompetentOrganizations(ids));
                list = propertyBasicsDao.reportListPage(page);
            }else {
                list = propertyBasicsDao.reportParentListPage(page);
            }


//            list = list.stream().filter(p -> StringUtil.isNotBlank(p.getString("orgCode"))).collect(Collectors.toList());
            ListResult listResult = new ListResult(CommonCode.SUCCESS);
            listResult.setList(valueListSet(list));
            listResult.setTotal(page.getTotal());
            return listResult;
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw new MyRuntimeException();
        }
    }

    /**
     * 导出excel
     *
     * @param pd
     * @param response
     */
    public void toExcel(PageData pd, HttpServletResponse response) throws Exception {
        List<PageData> list = listData(pd);
//        list = list.stream().filter(p -> StringUtil.isNotBlank(p.getString("orgCode"))).collect(Collectors.toList());
        String separator = File.separator;
        String exlPath = separator + "exceldemo" + separator + "property.xlsx";
        InputStream inputStream = this.getClass().getResourceAsStream(exlPath);
        String fileName = URLEncoder.encode("产权登记信息", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        // 设置响应头和客户端保存文件名
        response.setCharacterEncoding("utf-8");
        OutputStream outputStream = response.getOutputStream();// 取得输出流
        ExcelWriter excelWriter = EasyExcel.write(outputStream).withTemplate(inputStream).build();
        WriteSheet writeSheet = EasyExcel.writerSheet().build();
        FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
        excelWriter.fill(list, fillConfig, writeSheet);
        excelWriter.finish();
        inputStream.close();
        outputStream.close();
    }

    public void toExcel1(PageData pd, HttpServletResponse response) throws Exception {
        String pro_id = pd.getString("id");
        String excelName = "";
        //附件
        PageData p = propertyBasicsDao.findbyid(pro_id);
        //出资人情况
        List<PageData> list_con = contributorBasicsDao.find_parentId(pro_id);
        List<String> parentId = new ArrayList<>();
        //出资人类别
        parentId.add("057");
        //产权登记情况
        parentId.add("060");
        //企业级次
        parentId.add("001");
        //国资监管机构
        parentId.add("064");
        //企业类别
        parentId.add("045");
        //组织形式
        parentId.add("002");
        //经营状况
        parentId.add("007");
        //币种
        parentId.add("014");
        //合伙人类型
        parentId.add("079");
        //合伙人类别
        parentId.add("078");
        //出资方式
        parentId.add("080");
        //标的类型
        parentId.add("081");
        //产权填写所属部门
        parentId.add("111");
        //功能分类
        parentId.add("043");
        PageData p_o = new PageData();
        p_o.put("parentId", parentId);
        List<Tree> trees = baseInfoDao.findTree(p_o);
        for (Object o : p.keySet()) {
            if (Tools.isEmpty(p.getString(o))) {
                p.put(o, "");
            }
        }
        String nature = p.getString("nature");
        if ("0".equals(nature)) {
            excelName = "property0.xlsx";
        }else if ("1".equals(nature)){
            excelName = "property1.xlsx";
        } else if ("2".equals(nature)) {
            excelName = "property2.xlsx";
        }
        String separator = File.separator;
        String exlPath = separator + "exceldemo" + separator + "pm" + separator + excelName;
        String fileName = "产权信息.xls";
        InputStream inputStream = this.getClass().getResourceAsStream(exlPath);


        // 设置响应头和客户端保存文件名
        response.setCharacterEncoding("utf-8");
        // 设定输出文件头
        response.setHeader("Content-disposition", "attachment; filename="
                + new String(fileName.getBytes("GB2312"), "ISO8859-1"));
        // 定义输出类型
        response.setContentType("application/msexcel");
        // 取得输出流
        OutputStream outputStream = response.getOutputStream();
        response.reset();// 清空输出流

        ExcelWriter excelWriter = EasyExcel.write(outputStream).withTemplate(inputStream).build();

        FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();

        // 表一
        WriteSheet writeSheet = EasyExcel.writerSheet(0).build();

        if ("1".equals(nature)) {
            //币种处理
            String currency=p.getString("currency");
            currency=getBaseName(trees, currency);
            p.put("currency", currency);
            //是否特殊目的
            if(Tools.notEmpty(p.getString("isSpecial"))){
                p.put("isSpecial", "0".equals(p.getString("isSpecial"))?"否":"是");
            }
            List<PageData> list_share = shareholdingBasicsDao.find_parentId(pro_id);
            int a=1;
            for (PageData pageData : list_share) {
                pageData.put("index",a++);
            }
            excelWriter.fill(new FillWrapper("l", list_share), fillConfig, writeSheet);
//            p.put("list_share", list_share);
            p.put("netWorkingName", netWorkingName(p.getString("netWorking")));

        }

        p.put("stateFundedRelationName", stateFundedRelationName(p.getString("stateFundedRelation")));
        if ("2".equals(nature)) {
            //是否为私募投资基金
            if(Tools.notEmpty(p.getString("isPrivateFund"))){
                p.put("isPrivateFund", "0".equals(p.getString("isPrivateFund"))?"否":"是");
            }
            //币种处理
            if(Tools.notEmpty(p.getString("subscribedCurrency"))){
                p.put("subscribedCurrency", getBaseName(trees, p.getString("subscribedCurrency")));
            }

            List<PageData> list_PartnerSituation = partnerSituationBascicsDao.find_parentId(pro_id);
            int a=0;
            BigDecimal sumSubscribedCapital=new BigDecimal("0");
            BigDecimal sumPaidCapital =new BigDecimal("0");
            for (PageData pageData : list_PartnerSituation) {
                pageData.put("index",a++);
                if(Tools.notEmpty(pageData.getString("subscribedCapital"))){
                    sumSubscribedCapital=sumSubscribedCapital.add(new BigDecimal(pageData.getString("subscribedCapital")));
                }else{
                    pageData.put("subscribedCapital","0");
                }
                if(Tools.notEmpty(pageData.getString("paidCapital"))){
                    sumPaidCapital=sumPaidCapital.add(new BigDecimal(pageData.getString("paidCapital")));
                }else{
                    pageData.put("paidCapital","0");
                }

                //合伙人类型
                if(Tools.notEmpty(pageData.getString("type"))){
                    pageData.put("type", getBaseName(trees, pageData.getString("type")));
                }
                //合伙人类别
                if(Tools.notEmpty(pageData.getString("category"))){
                    pageData.put("category", getBaseName(trees, pageData.getString("category")));
                }
                //出资方式
                if(Tools.notEmpty(pageData.getString("way"))){
                    pageData.put("way", getBaseName(trees, pageData.getString("way")));
                }
            }
            p.put("sumSubscribedCapital", sumSubscribedCapital.toPlainString());
            p.put("sumPaidCapital", sumPaidCapital.toPlainString());
            p.put("listPartnerSituation", list_PartnerSituation);
            List<PageData> list_PartnerOutbound = partnerOutboundBasicsDao.find_parentId(pro_id);
            int b=0;
            BigDecimal sumInvestmentAmount=new BigDecimal("0");
            for (PageData pageData : list_PartnerOutbound) {
                pageData.put("index",b++);
                String industry = pageData.getString("industry");
                if (Tools.notEmpty(industry)) {
                    List<String> industrys = industryNames(industry);
                    String industryNames="";
                    if (industrys != null && industrys.size() > 0) {
                        industryNames = String.join("|", industrys);
                    }
                    pageData.put("industryName", industryNames);
                }

                //标的类型
                if(Tools.notEmpty(pageData.getString("type"))){
                    pageData.put("type", getBaseName(trees, pageData.getString("type")));
                }
                //是否实际控制
                if(Tools.notEmpty(pageData.getString("isControl"))){
                    pageData.put("isControl", "0".equals(pageData.getString("isControl"))?"否":"是");
                }

                if(Tools.notEmpty(pageData.getString("investmentAmount"))){
                    sumInvestmentAmount=sumInvestmentAmount.add(new BigDecimal(pageData.getString("investmentAmount")));
                }else{
                    pageData.put("investmentAmount","0");
                }
            }
//            p.put("listPartnerOutbound", list_PartnerOutbound);
            excelWriter.fill(new FillWrapper("l", list_PartnerOutbound), fillConfig, writeSheet);
            p.put("sumInvestmentAmount", sumInvestmentAmount.toPlainString());
        }

        //出资人情况
        int i = 0;
        BigDecimal sumContributionAmount = new BigDecimal("0");
        BigDecimal sumOrgPaidCapital = new BigDecimal("0");
        BigDecimal sumOrgSubscribedCapital = new BigDecimal("0");
        BigDecimal sumOriginalContributionAmount = new BigDecimal("0");
        BigDecimal sumOriginalPaidCapital = new BigDecimal("0");
        BigDecimal sumOriginalSubscribedCapital = new BigDecimal("0");
        BigDecimal sumEquityRatio=new BigDecimal("0");
        for (PageData pageData : list_con) {
            //出资额
            String contributionAmount = pageData.getString("contributionAmount");
            if (Tools.isEmpty(contributionAmount)) {
                contributionAmount = "0";
            }
            //出资额
            String originalContributionAmount = pageData.getString("originalContributionAmount");
            if (Tools.isEmpty(originalContributionAmount)) {
                originalContributionAmount = "0";
            }

            String orgPaidCapital = pageData.getString("orgPaidCapital");
            if (Tools.isEmpty(orgPaidCapital)) {
                orgPaidCapital = "0";
            }

            String originalPaidCapital = pageData.getString("originalPaidCapital");
            if (Tools.isEmpty(originalPaidCapital)) {
                originalPaidCapital = "0";
            }

            String orgSubscribedCapital = pageData.getString("orgSubscribedCapital");
            if (Tools.isEmpty(orgSubscribedCapital)) {
                orgSubscribedCapital = "0";
            }

            String originalSubscribedCapital = pageData.getString("originalSubscribedCapital");
            if (Tools.isEmpty(originalSubscribedCapital)) {
                originalSubscribedCapital = "0";
            }
            String equityRatio = pageData.getString("equityRatio");
            if (Tools.isEmpty(equityRatio)) {
                equityRatio = "0";
            }

            sumContributionAmount = sumContributionAmount.add(new BigDecimal(contributionAmount));
            sumOrgPaidCapital = sumOrgPaidCapital.add(new BigDecimal(orgPaidCapital));
            sumOrgSubscribedCapital = sumOrgSubscribedCapital.add(new BigDecimal(orgSubscribedCapital));
            sumOriginalContributionAmount = sumOriginalContributionAmount.add(new BigDecimal(originalContributionAmount));
            sumOriginalPaidCapital = sumOriginalPaidCapital.add(new BigDecimal(originalPaidCapital));
            sumOriginalSubscribedCapital = sumOriginalSubscribedCapital.add(new BigDecimal(originalSubscribedCapital));
            sumEquityRatio = sumEquityRatio.add(new BigDecimal(equityRatio));
            //出资人类别
            String category = pageData.getString("category");
            if (Tools.isEmpty(category)) {
                category = "";
            } else {
                category = getBaseName(trees, category);
            }
            pageData.put("category", category);
            pageData.put("index", String.valueOf(++i));
        }
        p.put("sumContributionAmount", sumContributionAmount.toPlainString());
        p.put("sumOrgPaidCapital", sumOrgPaidCapital.toPlainString());
        p.put("sumOrgSubscribedCapital", sumOrgSubscribedCapital.toPlainString());
        p.put("sumOriginalContributionAmount", sumOriginalContributionAmount.toPlainString());
        p.put("sumOriginalPaidCapital", sumOriginalPaidCapital.toPlainString());
        p.put("sumOriginalSubscribedCapital", sumOriginalSubscribedCapital.toPlainString());
        p.put("sumEquityRatio", sumEquityRatio.toPlainString());
//        p.put("list_con", list_con);

        if (Tools.notEmpty(p.getString("majorIndustries"))) {
            List<String> majorIndustries = industryNames(p.getString("majorIndustries"));
            String majorIndustriesNames="";
            if (majorIndustries != null && majorIndustries.size() > 0) {
                majorIndustriesNames = String.join("|", majorIndustries);
            }
            p.put("majorIndustriesNames",majorIndustriesNames);
        }
        excelWriter.fill(new FillWrapper("t", list_con), fillConfig, writeSheet);
//        p.put("list_con", list_con);

        //产权登记情况
        if(Tools.notEmpty(p.getString("situation"))){
            p.put("situation", getBaseName(trees, p.getString("situation")));
        }
        //企业级次
        if(Tools.notEmpty(p.getString("orgGradation"))){
            p.put("orgGradation", getBaseName(trees, p.getString("orgGradation")));
        }
        //所属部门
        if(Tools.notEmpty(p.getString("departments"))){
            p.put("departments", getBaseName(trees, p.getString("departments")));
        }
        //国资监管机构
        if(Tools.notEmpty(p.getString("stateOwnedInstitution"))){
            p.put("stateOwnedInstitution", getBaseName(trees, p.getString("stateOwnedInstitution")));
        }
        //企业类别
        if(Tools.notEmpty(p.getString("orgCategory"))){
            p.put("orgCategory", getBaseName(trees, p.getString("orgCategory")));
        }
        //组织形式
        if(Tools.notEmpty(p.getString("organizationForm"))){
            p.put("organizationForm", getBaseName(trees, p.getString("organizationForm")));
        }
        //经营状况
        if(Tools.notEmpty(p.getString("managementCondition"))){
            p.put("managementCondition", getBaseName(trees, p.getString("managementCondition")));
        }

        //是否国家出资企业
        if(Tools.notEmpty(p.getString("isStateFunded"))){
            p.put("isStateFunded", "0".equals(p.getString("isStateFunded"))?"否":"是");
        }
        //是否境外转投境内企业
        if(Tools.notEmpty(p.getString("isOverseasToDomestic"))){
            p.put("isOverseasToDomestic", "0".equals(p.getString("isOverseasToDomestic"))?"否":"是");
        }
        //是否已办工商
        if(Tools.notEmpty(p.getString("isBsHandle"))){
            p.put("isBsHandle", "0".equals(p.getString("isBsHandle"))?"否":"是");
        }
        //是否混改企业
        if(Tools.notEmpty(p.getString("isMix"))){
            p.put("isMix", "0".equals(p.getString("isMix"))?"否":"是");
        }
        //是否并表企业
        if(Tools.notEmpty(p.getString("isGroup"))){
            p.put("isGroup", "0".equals(p.getString("isGroup"))?"否":"是");
        }

        //功能分类
        if(Tools.notEmpty(p.getString("functionalCategoryName"))){
            p.put("functionalCategoryName", getBaseName(trees, p.getString("functionalCategoryName")));
        }

        excelWriter.fill(p, writeSheet);
        excelWriter.finish();
        outputStream.close();
    }


    public File toExcelBasics(String id, HttpServletResponse response) throws Exception {

        //附件
        PageData p = propertyBasicsDao.findbyid(id);

        List<String> parentId = new ArrayList<>();
        //企业级次
        parentId.add("001");
        //组织形式
        parentId.add("002");
        PageData codePd = new PageData();
        codePd.put("parentId", parentId);
        List<Tree> trees = baseInfoDao.findTree(codePd);

        String nature = p.getString("nature");
        List<ContributorInfoWordBean> wordBeanList = new ArrayList<>();
        ContributorInfoWordBean totalWordBean = ContributorInfoWordBean.builder()
                .index("合计").contributor("-").equityRatio("100%").build();
        if ("2".equals(nature)) {
            List<PageData> listPartnerSituation = partnerSituationBascicsDao.find_parentId(id);
            if (StringUtil.isBlank(p.getString("regDate"))){
                p.put("regDate", p.getString("establishmentDate"));
            }
            if (CollectionUtil.isNotEmpty(listPartnerSituation)){
                for (int i = 0; i < listPartnerSituation.size(); i++) {
                    PageData pageData = listPartnerSituation.get(i);
                    wordBeanList.add(ContributorInfoWordBean.builder().index(String.valueOf(i + 1))
                            .contributor(pageData.getString("name"))
                            .orgPaidCapital(pageData.getString("paidCapital"))
                    .orgSubscribedCapital(pageData.getString("subscribedCapital"))
                    .equityRatio(BigDecimalUtil.toShortString(pageData.getString("subscribedProportion"), 2)).build());
                    if (StringUtil.isNotBlank(wordBeanList.get(i).getEquityRatio())){
                        wordBeanList.get(i).setEquityRatio(wordBeanList.get(i).getEquityRatio() + StringPool.PERCENT);
                    }
                    totalWordBean.setOrgSubscribedCapital(BigDecimalUtil.toPlanString(BigDecimalUtil
                            .add(BigDecimalUtil.toBigdecimal(totalWordBean.getOrgSubscribedCapital()),
                                    BigDecimalUtil.toBigdecimal(wordBeanList.get(i).getOrgSubscribedCapital()))));
                    totalWordBean.setOrgPaidCapital(BigDecimalUtil.toPlanString(BigDecimalUtil
                            .add(BigDecimalUtil.toBigdecimal(totalWordBean.getOrgPaidCapital()),
                                    BigDecimalUtil.toBigdecimal(wordBeanList.get(i).getOrgPaidCapital()))));
                }
            }
        }else {
            //出资人情况
            List<PageData> listCon = contributorBasicsDao.find_parentId(id);
            if (CollectionUtil.isNotEmpty(listCon)) {
                for (int i = 0; i < listCon.size(); i++) {
                    PageData pageData = listCon.get(i);
                    wordBeanList.add(ContributorInfoWordBean.builder().index(String.valueOf(i + 1))
                            .contributor(pageData.getString("contributor"))
                            .orgPaidCapital(pageData.getString("orgPaidCapital"))
                            .orgSubscribedCapital(pageData.getString("orgSubscribedCapital"))
                            .equityRatio(BigDecimalUtil.toShortString(pageData.getString("equityRatio"), 2)).build());
                    if (StringUtil.isNotBlank(wordBeanList.get(i).getEquityRatio())){
                        wordBeanList.get(i).setEquityRatio(wordBeanList.get(i).getEquityRatio() + StringPool.PERCENT);
                    }
                    totalWordBean.setOrgSubscribedCapital(BigDecimalUtil.toPlanString(BigDecimalUtil
                            .add(BigDecimalUtil.toBigdecimal(totalWordBean.getOrgSubscribedCapital()),
                                    BigDecimalUtil.toBigdecimal(wordBeanList.get(i).getOrgSubscribedCapital()))));
                    totalWordBean.setOrgPaidCapital(BigDecimalUtil.toPlanString(BigDecimalUtil
                            .add(BigDecimalUtil.toBigdecimal(totalWordBean.getOrgPaidCapital()),
                                    BigDecimalUtil.toBigdecimal(wordBeanList.get(i).getOrgPaidCapital()))));
                }
            }
        }
        wordBeanList.add(totalWordBean);

        //企业级次
        if(Tools.notEmpty(p.getString("orgGradation"))){
            p.put("orgGradation", getBaseName(trees, p.getString("orgGradation")));
        }

        //组织形式
        if(Tools.notEmpty(p.getString("organizationForm"))){
            p.put("organizationForm", getBaseName(trees, p.getString("organizationForm")));
        }
        p.put("wordBeanList",wordBeanList);

        String realPath = environment.getProperty("doc.path") + id + ".doc";
        File file = WordUtil.generateWord(p, realPath, "产权信息.doc", "propertyBasicInfo.ftl");
        String fileName = new String(file.getName().getBytes("GB2312"), "ISO_8859_1");
        response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
        InputStream inputStream = new FileInputStream(file);
        // 激活下载操作
        OutputStream os = response.getOutputStream();
        // 循环写入输出流
        byte[] b = new byte[2048];
        int length;
        while ((length = inputStream.read(b)) > 0) {
            os.write(b, 0, length);
        }
        // 这里主要关闭。
        os.close();
        inputStream.close();
        return file;
    }

    public String findNameById(String id) {
        String orgName = "";
        try {
            PageData p = propertyBasicsDao.findbyid(id);
            if (CollectionUtil.isNotEmpty(p)) {
                orgName = (String) p.get("orgName");
            }
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw new MyRuntimeException();
        }
        return orgName;

    }

    public List<String> findChildrenIds(String id) {
        try {
            PageData pd = propertyBasicsDao.findbyid(id);
            if (pd != null) {
                TreeUtli treeUtli = new TreeUtli();
                List<PageData> list_all = propertyBasicsDao.list(null);
                List<PageData> l = treeUtli.getChlid1(pd.getString("id"), list_all);
                return setChildrenIds(l);
            }
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw new MyRuntimeException();
        }
        return new ArrayList<>();
    }

    private List<String> setChildrenIds(List<PageData> children) {
        List<String> childrenIds = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(children)) {
            for (PageData child : children) {
                childrenIds.add((String) child.get("id"));
                if (child.containsKey("children")) {
                    List<PageData> list = (List<PageData>) child.get("children");
                    childrenIds.addAll(setChildrenIds(list));
                }
            }
        }
        return childrenIds;
    }

    /**
     * 获取国家出资企业名称
     *
     * @param pid
     * @return
     */
    public String getStateName(String pid, PageData p) {
        try {
            String s = "";
            if (!"0".equals(pid)) {

                if ("001001".equals(p.getString("orgGradation"))) {
                    s = p.getString("orgName");
                } else {
                    List<PageData> list = propertyBasicsDao.list(null);
                    s = getStateName(p.getString("parentId"), list);
                }
            }
//            ObjResult objResult = new ObjResult(CommonCode.SUCCESS);
//            PageData pd = new PageData();
//            pd.put("stateName", s);
//            objResult.setPageData(pd);
//            return objResult;
            return s;
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw new MyRuntimeException();
        }
    }

    private String getStateName(String pid, List<PageData> list) {
        for (PageData pageData : list) {
            if (pageData.getString("id").equals(pid)) {
                if ("001001".equals(pageData.getString("orgGradation"))) {
                    return pageData.getString("orgName");
                } else {
                    String s = getStateName(pageData.getString("parentId"), list);
                    if (Tools.notEmpty(s)) {
                        return s;
                    }
                }
            }
        }
        return "";
    }
}
